package com.my.interview.I18n;

import java.io.BufferedInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.*;

public class I18nResources {

    private static final String XML_LITERAL = "xml";

    private static String lang = System.setProperty("pmd.language","zh");

    /**
     * 当前的地理位
     */
    private static Locale currentLocal;

    /**
     * 国际化资源绑定类
     */
    private static ResourceBundle resourceBundle;


    public static ResourceBundle changeLanguage(String lang){

        Locale locale = Locale.CHINESE.getLanguage().equals(lang) ? Locale.CHINESE : Locale.ENGLISH;
        return changeLanguage(locale);

    }

    public static ResourceBundle changeLanguage(Locale locale){

        if(currentLocal != null && currentLocal.equals(locale)){
            return resourceBundle;
        }
        currentLocal = locale;
        resourceBundle = ResourceBundle.getBundle("messages", locale, new XmlControl());
        return resourceBundle;
    }

    public static String getMessage(String key){
        return resourceBundle.getString(key).trim();
    }

    /**
     * Object... 表示该方法可以传递多个不同的参数类型
     * @param key
     * @param params
     * @return
     */
    public static String getMessage(String key, Object... params){
        String value = getMessage(key);
        if(params == null || params.length == 0){
            return value;
        }
        return String.format(value, params);
    }

    public static String getMessageWithExceptionHandled(String key){
        try{
           return resourceBundle.getString(key).trim();
        }catch (MissingResourceException e){
            return key;
        }
    }


    public static class XmlResourceBundle extends ResourceBundle{

        private Properties props;

        XmlResourceBundle(InputStream stream){
            props = new Properties();
            try {
                props.loadFromXML(stream);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        @Override
        protected Object handleGetObject(String key) {
            return props.getProperty(key);
        }

        @Override
        public Enumeration<String> getKeys() {

            List<String> keys = new ArrayList<>();
            Enumeration<Object> enumeration = props.keys();
            while(enumeration.hasMoreElements()){
                keys.add((String)enumeration.nextElement());
            }
            return Collections.enumeration(keys);
        }
    }

    public static class XmlControl extends ResourceBundle.Control {

        @Override
        public List<String> getFormats(String baseName) {
            System.out.println(baseName);
            if(baseName == null){
                throw new NullPointerException();
            }
            System.out.println("=========" + Collections.singletonList(XML_LITERAL));
            return Collections.singletonList(XML_LITERAL);
        }

        @Override
        public Locale getFallbackLocale(String baseName, Locale locale) {
            return null;
        }

        @Override
        public ResourceBundle newBundle(String baseName, Locale locale, String format, ClassLoader loader, boolean reload) throws IllegalAccessException, InstantiationException, IOException {

            if(baseName == null || locale == null
            || format == null || loader == null){
                throw new NullPointerException();
            }
            ResourceBundle bundle = null;
            if(XML_LITERAL.equals(format)){
                String bundleName = toBundleName(baseName, locale);
                String resourceName = toResourceName(bundleName, format);
                InputStream inputStream;
                inputStream = getInputStream(loader,resourceName);
                /*if(reload){
                    inputStream = getInputStream(loader,resourceName);
                }
                else {
                    inputStream = loader.getResourceAsStream(resourceName);
                    System.out.println("load========");
                }*/
                if(inputStream != null){
                    BufferedInputStream bis = new BufferedInputStream(inputStream);
                    bundle = new XmlResourceBundle(bis);
                    bis.close();
                }
            }
            return bundle;
        }

        private InputStream getInputStream(ClassLoader loader, String resourceName)
        throws IOException{

            URL url = loader.getResource(resourceName);
            if(url == null){
                return null;
            }
            URLConnection connection = url.openConnection();
            if(connection == null){
                return null;
            }

            connection.setUseCaches(false);
            return connection.getInputStream();
        }
    }

    public static void main(String[] args) {

        ResourceBundle bundle = ResourceBundle.getBundle("messages", Locale.CHINESE, new XmlControl());
        String res = bundle.getString("java.comment.ClassMustHaveAuthorRule.rule.msg");
        System.out.println("res=======" + res);
    }
}
